<template>
  <t-dialog
    v-model:visible="show"
    :width="600"
    :header="plugin.t('btn.create')"
    :onConfirm="() => form.submit()"
    destroyOnClose
    :closeOnOverlayClick="false"
  >
    <template #body>
      <t-form ref="form" :data="formData" :rules="formRule" label-align="top" @submit="onSubmit" style="overflow: hidden;">
        <t-row :gutter="20">
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.code')" name="code">
              <t-input v-model="formData.code"/>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.number')" name="number">
              <t-input v-model="formData.number" />
            </t-form-item>
          </t-col>
        </t-row>
        
        <t-row :gutter="20" style="margin-top: 20px">
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.name')" name="name">
              <t-input v-model="formData.name"/>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.price')" name="price">
              <t-input-number :value="Number(formData.price)" @change="value => formData.price = value" theme="normal" style="width: 100%">
                <template #suffix>
                  <t-icon name="arrow-left" style="cursor: pointer" @click="onPriceMath()" />
                  <t-icon name="arrow-right" style="cursor: pointer" @click="onPriceMath(true)" />
                </template>
              </t-input-number>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row :gutter="20" style="margin-top: 20px">
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.tax_id')">
              <t-select v-model="formData.tax_id">
                <t-option label="-" :value="0" />
                <t-option v-for="item in taxStore.getList()" :value="item.id" :label="item.name" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="plugin.t('form.price_cost')" name="price_cost">
              <t-popup :content="plugin.t('form.price_cost_message')" placement="top-left" destroy-on-close>
                <t-input-number :decimalPlaces="4" :value="Number(formData.price_cost)" @change="value => formData.price_cost = value" theme="normal" style="width: 100%">
                  <template #suffix>
                    <t-icon name="arrow-left" style="cursor: pointer" @click="onPriceCost" />
                  </template>
                </t-input-number>
              </t-popup>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row :gutter="20" style="margin-top: 20px">
          <t-col :span="6" v-if="supplier_id > 0">
            <t-form-item :label="plugin.t('form.supplier_id')">
              <t-input readonly v-model="supplier_name" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </template>
    <template #footer>
      <t-button theme="primary" :loading="loading" @click="form.submit()">
        {{ plugin.t('btn.create') }}
      </t-button>
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import goodsStore from '../store'
  import taxStore from '@/plugin/config/store/tax'
  import { get } from '@/api/store/goods'
  import index from '../index'

  const props = defineProps(['supplier_id', 'supplier_name'])
  const emit = defineEmits(['post'])
  const plugin = index.plugin

  const show = ref(false)
  const loading = ref(false)
  const form = ref(null)
  const formData = ref({})
  const formRule = {
    name: [{ required: true, message: ' ', type: 'error' }],
    number: [{ required: true, message: ' ', type: 'error' }],
    code: [{ required: true, message: ' ', type: 'error' }],
    price: [{ required: true, message: ' ', type: 'error' }]
  }
  const open = () => {
    formData.value = {
      tax_id: taxStore.default(),
      name: '',
      code: '',
      number: '',
      price: 0,
      price_cost: 0,
    }
    show.value = true
  }

  // 创建真实商品
  const onSubmit = ({ validateResult }) => {
    if (validateResult === true) {
      loading.value = true
      const data = formData.value
      data.supplier_id = props.supplier_id ?? 0
      goodsStore.update(data).then(res => {
        app.message('success', 'message.' + res.message)
        show.value = false
        // 搜索本次添加的商品
        get(data).then(res => {
          if(res.data.length) {
            onPost(res.data[0])
          }
        })
      }).catch(err => {
        app.message('error', 'message.error.' + err.message)
      }).finally(() => {
        loading.value = false
      })
    }
  }

  // 添加临时商品
  const onTemp = async() => {
    if(await form.value.validate() === true) {
      onPost(formData.value)
    }
  }

  // 事件
  const onPost = data => {
    show.value = false
    emit('post', data)
  }

  // 推算价格
  const onPriceMath = (type = false) => {
    const func = type ? app.math.addpro : app.math.divpro

    formData.value.price = func(
      formData.value.price, 
      taxStore.tax(formData.value.tax_id)
    )
  }

  // 成本价回推
  const onPriceCost = () => {
    formData.value.price_cost = app.math.factory(formData.value.price_cost).divpro(
      taxStore.tax(formData.value.tax_id)
    ).format(4)
  }

  taxStore.get()

  defineExpose({ open })
</script>